package cz.cvut.manatee.processManager;

import com.phrasebox.manatee.*;
import java.util.HashMap;
import java.util.Map;
import cz.cvut.manatee.processManager.ThreadRunnable;

public class OptimizedCorpus {
	
	private static class CorpusMapContent {
		private final Corpus corpus;
		private final String name;
		
		public CorpusMapContent(Corpus corpus, String name) {
			this.corpus = corpus;
			this.name   = name;
		}
		
		public Corpus getCorpus() {
			return this.corpus;
		}
		
		public boolean equal(String other) {
			return this.name.equalsIgnoreCase(other);
		}
	}
	
	private static Map<ThreadRunnable, CorpusMapContent> instances = new HashMap<ThreadRunnable, CorpusMapContent>();
	
	public static Corpus getInstance(ThreadRunnable thread, String name) {
		if (OptimizedCorpus.instances.containsKey(thread)) {
			// vlakno je jiz registrovano - jiz drive pozadovalo korpus
			CorpusMapContent saved = OptimizedCorpus.instances.get(thread);
			if (saved != null) {
				if (saved.equal(name)) {
					// v mape byl ulozen stejny korpus
					System.out.println("OptimCorp: zadost o korpus, jiz existuje. Vytvoreno: "+OptimizedCorpus.instances.size());
					return saved.getCorpus();
				}
			}
		}
		
		// vlakno zada poprve nebo vlakno obsahovalo jiny korpus
		System.out.println("OptimCorp: zadost o korpus, jdu tvorit novy. Zatim vytvoreno: "+OptimizedCorpus.instances.size());
		Corpus corp = new Corpus(name);
		OptimizedCorpus.instances.put(thread, new CorpusMapContent(corp, name));
		return corp;
	}
	
	public static void reset() {
		OptimizedCorpus.instances.clear();
	}
}
